<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-input v-model="search.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="onsale">批量上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale">批量下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;" height="500">
      <el-table-column type="selection" width="55" fixed>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="150" fixed>
      </el-table-column>
      <el-table-column prop="cover" label="封面" width="120">
        <template slot-scope="scope">
          <img :src="scope.row.cover" width="100" height="100"/>
        </template>
      </el-table-column>
      <el-table-column prop="saleprice" label="原价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="售价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="isnew" label="是否新车" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.isnew == 1" style="color: #5e7382">是</span>
          <span v-if="scope.row.isnew == 0" style="color: coral">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="reigstertime" label="上牌时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="mileage" label="里程" width="80" sortable>
      </el-table-column>
      <el-table-column prop="shopname" label="店铺名称" width="180" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: #5e7382">上架</span>
          <span v-if="scope.row.state == 0" style="color: coral">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="costeffective" label="是否超值" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.costeffective == 1" style="color: #5e7382">是</span>
          <span v-if="scope.row.costeffective == 0" style="color: coral">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="rushsale" label="是否急售" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.rushsale == 1" style="color: #5e7382">是</span>
          <span v-if="scope.row.rushsale == 0" style="color: coral">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="quasinewcar" label="是否准新车" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.quasinewcar == 1" style="color: #5e7382">是</span>
          <span v-if="scope.row.quasinewcar == 0" style="color: coral">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="transitivecountry" label="是否可迁全国" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.transitivecountry == 1" style="color: #5e7382">是</span>
          <span v-if="scope.row.transitivecountry == 0" style="color: coral">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="carType.name" label="类型" width="100" sortable>
      </el-table-column>
      <el-table-column prop="seller.username" label="销售顾问" width="100" sortable>
      </el-table-column>
      <el-table-column prop="auditstate" label="审核状态" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.auditstate == 1" style="color: #5e7382">审核通过</span>
          <span v-if="scope.row.auditstate == 0" style="color: coral">审核驳回</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" fixed="right" width="150">
        <template scope="scope">
          <el-row>
            <el-col :span="12">
              <el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-button size="small">审核</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="small">提交审核</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" size="small" @click="handleResource(scope.$index, scope.row)">资源维护
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" size="small" @click="handleDel(scope.$index, scope.row)">上传检测报告</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
          @size-change: 当涉及的每页条数发生改变的时候触发的函数
          @current-change: 页数发生改变
          :current-page 当前第几页
          :page-sizes="[3, 5, 10, 20]" : 设定每页的条数
          :page-size="this.search.pageSize" 每页条数
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.search.currentPage"
          :page-sizes="[3, 5, 10, 20,100]"
          :page-size="this.search.pageSize"
          style="float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增/修改" :visible.sync="carFormVisible" :close-on-click-modal="false">
      <el-form :model="carForm" label-width="80px" ref="carForm">
        <el-form-item label="标题">
          <el-input v-model="carForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="coverHandleRemove"
              :on-success="coverHandleSuccess"
              :file-list="coverFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="carForm.saleprice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="carForm.costprice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否新车">
          <el-radio-group v-model="carForm.isnew">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上牌时间">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="carForm.reigstertime"
              type="date"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="里程数">
          <el-input v-model="carForm.mileage" style="width:220px;" type="number" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="超值">
          <el-radio-group v-model="carForm.costeffective">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="急售">
          <el-radio-group v-model="carForm.rushsale">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="准新车">
          <el-radio-group v-model="carForm.quasinewcar">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可迁全国">
          <el-radio-group v-model="carForm.transitivecountry">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-cascader v-model="carForm.type"
                       :options="carTypeTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="基本信息">
          <quill-editor v-model="carForm.carDetail.info" :options="quillOptions">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--    资源维护界面-->
    <el-dialog title="资源维护" :visible.sync="resourcesFormVisible" :close-on-click-modal="false">
      <el-form :model="resourcesForm" label-width="80px" ref="addForm">
        <el-form-item label="主图" prop="img">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="imgHandleRemove"
              :on-success="imgHandleSuccess"
              :file-list="imgFileList"
              name="file"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="副图" prop="viceImg">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="viceImgHandleRemove"
              :on-success="viceImgHandleSuccess"
              :file-list="viceImgFileList"
              name="file"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="更多图片" prop="moreImg">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastDfs/upload"
              :on-remove="moreImgHandleRemove"
              :on-success="moreImgHandleSuccess"
              :file-list="moreImgFileList"
              name="file"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resourcesFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="resourcesSubmit">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import {quillEditor} from "vue-quill-editor"; // 在页面中引入富文本编辑框的组件
import quillConfig from "../../common/js/quill-config";
import 'quill/dist/quill.core.css'; // 引入样式
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOptions: quillConfig,
      coverFileList: [],//上传列表
      search: {
        keyword: '',
        pageSize: 10,
        currentPage: 1
      },
      pageInfo: {
        list: [],
        total: 0
      },
      addLoading: false,
      listLoading: false,
      sels: [],//列表选中列
      carFormVisible: false,//新增修改界面是否显示
      resourcesFormVisible: false,//资源维护界面是否显示
      carFormLoading: false,
      carFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      // 资源维护界面数据
      resourcesForm: {
        carId: null,
        fileList: []
      },
      imgFileList: [],
      viceImgFileList: [],
      moreImgFileList: [],
      //新增修改界面数据
      carForm: {
        id: null,
        title: "",
        cover: "",
        saleprice: 0,
        costprice: 0,
        isnew: 0,
        reigstertime: "",
        mileage: null,
        costeffective: 0,
        rushsale: 0,
        quasinewcar: 0,
        transitivecountry: 0,
        type: {
          id: null,
          name: ""
        },
        typeId: null,
        carDetail: {
          info: ""
        }
      },
      carTypeTree: []
    }
  },
  methods: {
    // 批量上架和批量下架
    onsale(){
      // 获取当前被选中数据的id数组
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/car/onsale',ids).then((res) => {
          this.listLoading = false;
          res = res.data
          if(res.success){
            this.$message({
              message: res.data,
              type: 'success'
            });
          }else{
            this.$message({
              message: res.msg,
              type: 'error'
            });
          }
          this.getCars();
        });
      }).catch(() => {

      });
    },
    offsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/car/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getCars();
        });
      }).catch(() => {

      });
    },
    //文件上传成功回调
    coverHandleSuccess(response, file, fileList) {
      this.carForm.cover = response.data;
    },
    //文件删除
    coverHandleRemove(file, fileList) {
      var filePath = file.response.data;
      this.$http.delete("/fastDfs/delete?filePath=" + filePath)
          .then(res => {
            res = res.data;
            if (res.success) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.carForm.cover = ''
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
    },
    // 副图上传
    viceImgHandleSuccess(response, file, fileList) {
      this.viceImgFileList = fileList;
    },
    viceImgHandleRemove(file, fileList) {
      console.log(file.response)
      var filePath = file.response ? file.response.data : file.url;
      this.$http.delete("/fastDfs/delete?filePath=" + filePath)
          .then(res => {
            res = res.data;
            if (res.success) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.viceImgFileList = fileList
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
    },
    // 主图上传
    imgHandleSuccess(response, file, fileList) {
      this.imgFileList = fileList
    },
    imgHandleRemove(file, fileList) {
      var filePath = file.response ? file.response.data : file.url;
      this.$http.delete("/fastDfs/delete?filePath=" + filePath)
          .then(res => {
            res = res.data;
            if (res.success) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.imgFileList = fileList
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
    },
    // 更多图片上传
    moreImgHandleSuccess(response, file, fileList) {
      this.moreImgFileList = fileList
    },
    moreImgHandleRemove(file, fileList) {
      var filePath = file.response ? file.response.data : file.url;
      this.$http.delete("/fastDfs/delete?filePath=" + filePath)
          .then(res => {
            if (res.data.success) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.moreImgFileList = fileList
            } else {
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    // 资源维护提交
    resourcesSubmit() {
      let resourcesFileList = []
      this.dealResourcesImgFileList(resourcesFileList);
      this.resourcesForm.fileList = resourcesFileList;
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.$http.put("/carResources/batch", this.resourcesForm)
            .then(res => {
              res = res.data
              if (res.success) {
                this.$message({message: '操作成功', type: 'success'});
                this.search.currentPage = 1
                this.getCars();
                this.resourcesFormVisible = false;
                this.resourcesForm = {
                  carId: null,
                  fileList: []
                }
              } else {
                this.$message({message: res.msg, type: 'error'});
              }
            })
            .catch(res => {
            })
      });
    },
    dealResourcesImgFileList(resourcesFileList) {
      if (this.imgFileList != null && this.imgFileList.length > 0) {
        for (let i = 0; i < this.imgFileList.length; i++) {
          let url = this.imgFileList[i].response.data
          resourcesFileList.push({resourceUrl: url, carId: this.resourcesForm.carId, type: 1});
        }
      }
      if (this.viceImgFileList != null && this.viceImgFileList.length > 0) {
        for (let i = 0; i < this.viceImgFileList.length; i++) {
          let url = this.viceImgFileList[i].response.data
          resourcesFileList.push({resourceUrl: url, carId: this.resourcesForm.carId, type: 2});
        }
      }
      if (this.moreImgFileList != null && this.moreImgFileList.length > 0) {
        for (let i = 0; i < this.moreImgFileList.length; i++) {
          let url = this.moreImgFileList[i].response.data
          resourcesFileList.push({resourceUrl: url, carId: this.resourcesForm.carId, type: 3});
        }
      }
    },
    // 点击查询
    getSearch() {
      this.search.currentPage = 1;
      this.getCars()
    },
    handleSizeChange(val) {
      this.search.pageSize = val
      this.getCars();
    },

    handleCurrentChange(val) {
      this.search.currentPage = val;
      this.getCars();
    },
    //获取部门列表
    getCars() {
      // 发送请求 axios请求
      this.$http.post("/car", this.search)
          .then(res => {
            var data = res.data;
            if (data.success) {
              // this.pageInfo.list = data.data.list
              // this.pageInfo.total = data.data.total
              this.pageInfo = data.data
            }
          }).catch(res => {

      })
    },
    // 资源维护
    handleResource(index, row) {
      this.resourcesFormVisible = true;
      this.resourcesForm.carId = row.id;
      this.imgFileList = []
      this.viceImgFileList = []
      this.moreImgFileList = []
      this.getCarResourcesById(row.id);
    },
    getCarResourcesById(carId) {
      this.$http.get("/carResources/carId/" + carId)
          .then(result => {
            result = result.data;
            if (result.success) {
              for (var i = 0; i < result.data.length; i++) {
                var obj = result.data[i];
                var imgurl = obj.resourceUrl;
                var name = imgurl.substring(imgurl.lastIndexOf("/") + 1);
                if (obj.type == 1) {
                  this.imgFileList.push({name: name, url: imgurl, response: {data: imgurl}})
                }
                if (obj.type == 2) {
                  this.viceImgFileList.push({name: name, url: imgurl, response: {data: imgurl}})
                }
                if (obj.type == 3) {
                  this.moreImgFileList.push({name: name, url: imgurl, response: {data: imgurl}})
                }
              }
            }
          }).catch(res => {

      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        if(row.state === 1){
          this.$message({message: '该车辆上架，不能删除，请先下架', type: 'error'});
          return
        }
        this.listLoading = true;
        //NProgress.start();

        this.$http.delete("/car/" + row.id)
            .then(res => {
              res = res.data;
              if (res.success) {
                this.$message({message: '删除成功', type: 'success'});
                this.search.currentPage = 1
                this.getCars()
                this.listLoading = false;
              }
            }).catch(res => {

        })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.coverFileList = [{name: row.cover, url: row.cover, response: {data: row.cover}}]
      this.carFormVisible = true;
      this.carForm = row;
      if (row.carType) {
        this.carForm.type = row.carType.id
      }else{
        this.carForm.type = 0
      }
      this.getCarTypeTree();
      this.$http.get("/carDetail/carId/" + row.id)
          .then(res => {
            res = res.data;
            if (res.success) {
              this.carForm.carDetail = res.data;
            }
          }).catch(res => {
      })
    },
    //显示新增界面
    handleAdd: function () {
      this.carFormVisible = true;
      this.carForm = {
        id: null,
        title: "",
        cover: "",
        saleprice: 0,
        costprice: 0,
        isnew: 0,
        reigstertime: "",
        mileage: null,
        costeffective: 0,
        rushsale: 0,
        quasinewcar: 0,
        transitivecountry: 0,
        type: {
          id: null,
          name: ""
        },
        typeId: null,
        carDetail: {
          info: ""
        }
      }
      this.coverFileList = []
      this.getCarTypeTree();
    },
    getCarTypeTree() {
      this.$http.get("/carType/tree")
          .then(res => {
            res = res.data;
            if (res.success) {
              this.carTypeTree = res.data
            }
          }).catch(res => {
      })
    },
    //新增
    save: function () {
      this.$refs.carForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let para = Object.assign({}, this.carForm);
            let type = para.type;
            if (type) {
              para.typeId = type[type.length - 1]
            }
            this.$http.put("/car", para)
                .then(res => {
                  res = res.data
                  if (res.success) {
                    this.$message({message: '操作成功', type: 'success'});
                    this.addLoading = false;
                    this.search.currentPage = 1
                    this.getCars()
                    this.carFormVisible = false;
                    // this.carForm.cover = ''
                    this.coverFileList = []
                  }
                })
                .catch(res => {
                  this.$message({message: '操作失败,系统故障,请稍后再试！', type: 'error'});
                })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/car", ids)
            .then(res => {
              console.log(res)
              var data = res.data;
              if (data.success) {
                this.$message({message: '删除成功', type: 'success'});
                this.listLoading = false
                this.getSearch();
              }
            }).catch(res => {

        })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getCars();
  }
}

</script>

<style scoped>

</style>